package com.chen.facemanager.interceptor;

import com.alibaba.fastjson.JSON;
import com.chen.facemanager.annotations.AccessLimit;
import com.chen.facemanager.redis.AccessKey;
import com.chen.facemanager.redis.RedisService;
import com.chen.facemanager.util.CodeMsg;
import com.chen.facemanager.util.HttpHelper;
import com.chen.facemanager.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @ClassName AccessLimitInterceptor
 * @Description
 * @Author Mr-CHEN
 * @Date 2019/8/20 19:06
 * @Version V1.0
 **/

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //请求controller中的方法名
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //解析HandlerMethod
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBean().getClass().getSimpleName();
        String phone = request.getHeader("phone");
        //接口限流
        AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
        if(accessLimit == null) {
            return true;
        }

        int maxCount = accessLimit.maxCount();
        int seconds = accessLimit.seconds();

        if (!StringUtils.equals(methodName, "getCode")) {
            //如果是拦截到登录请求，不打印参数，因为参数里面有密码，全部会打印到日志中，防止日志泄露
            return true;
        }

        AccessKey ak = AccessKey.withExpire;
        Integer count = redisService.get(ak, phone, Integer.class);
        if (count == null){
            redisService.set(ak,phone,1,seconds);
        }else if(count <= maxCount){
            render(response, CodeMsg.ACCESS_LIMIT_REACHED);
            return false;
//            redisService.incr(ak, phone);
        }else {
            render(response, CodeMsg.ACCESS_LIMIT_REACHED);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JSON.toJSONString(Result.error(cm));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

}